import type { IMiddleware } from "koa-router";

import { User } from "../model";
import { UserStatus } from "../model/user";
import { makeResponse, HttpStatusCode } from "../util/response";

// 获取所有用户
export const getUsers: IMiddleware = async ctx => {
  // 1. 获取 query 参数
  const current = ctx.query.current as any as number;
  const limit = ctx.query.limit as any as number;
  const status = ctx.query.status as any as UserStatus;
  const name = ctx.query.name as string;
  const sort = (ctx.query.sort as any as number) ?? -1;

  // 1.1 获取前面拿到的 total
  const { total } = ctx.state;

  // 2. 连接数据库获取 users
  const skipCount = (current - 1) * limit;
  const query = User.find({})
    .skip(skipCount)
    .limit(limit)
    .sort({ create_at: sort });

  // 2.1 根据参数筛选数据
  if (name) query.where("name").regex(name);
  if (status) query.where("status").equals(status);
  const result = await query.exec();

  console.log(ctx.state);

  // 3. 返回所有 users 包括 total
  makeResponse(ctx, HttpStatusCode.Ok, { result, total });
};

// 获取单个用户
export const getUser: IMiddleware = async ctx => {
  const { result } = ctx.state;

  makeResponse(ctx, HttpStatusCode.Ok, result);
};

// 新增用户
export const createUser: IMiddleware = async ctx => {
  const user = new User(ctx.request.body);
  await user.save();
  const userJSON = user.toJSON();
  delete userJSON.password;

  makeResponse(ctx, HttpStatusCode.Created, userJSON);
};

// 更新用户
export const updateUser: IMiddleware = async ctx => {
  const { id } = ctx.params;
  const { name } = ctx.request.body;
  await User.findByIdAndUpdate(id, { name });
  const result = await User.findById(id);

  makeResponse(ctx, HttpStatusCode.Ok, result);
};

// 删除用户
export const deleteUser: IMiddleware = async ctx => {
  const { id } = ctx.params;
  await User.findByIdAndDelete(id);

  makeResponse(ctx, HttpStatusCode.NoContent);
};
